package pers.lmd.common.utils;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import pers.lmd.common.constant.CacheConstants;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author lmd
 * @Date 2023/4/7 18:50
 */
public class VerificationCodeUtil extends HttpServlet {

    public static void createVerificationCode(HttpServletRequest request, HttpServletResponse response, String uuid) throws IOException {

        // 获得生成的验证码字符
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 7);
        String captcha = circleCaptcha.getCode();

        // 自定义Session
        circleCaptcha.write(response.getOutputStream());
        request.getSession().setAttribute("captcha", captcha);
        circleCaptcha.createCode();

        // 保存验证码到 redis
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        SaSessionCustomUtil.getSessionById(verifyKey).set(verifyKey, captcha).updateTimeout(60);

        // 输出验证码
        System.out.println("真实的验证码是：" + captcha);
    }
}
